package net.wicp.tams.common.binlog.parser.event;

import net.wicp.tams.common.binlog.parser.LogBuffer;
import net.wicp.tams.common.binlog.parser.LogEvent;

/**
 * @author jianghang 2013-4-8 上午12:36:29
 * @version 1.0.3
 * @since mysql 5.6 / mariadb10
 */
public class GtidLogEvent extends LogEvent {

	// / Length of the commit_flag in event encoding
	public static final int ENCODED_FLAG_LENGTH = 1;
	// / Length of SID in event encoding
	public static final int ENCODED_SID_LENGTH = 16;

	private boolean commitFlag;

	private String gtid;

	private String source;

	public GtidLogEvent(LogHeader header, LogBuffer buffer, FormatDescriptionLogEvent descriptionEvent) {
		super(header);

		final int commonHeaderLen = descriptionEvent.commonHeaderLen;
		// final int postHeaderLen = descriptionEvent.postHeaderLen[header.type
		// - 1];

		buffer.position(commonHeaderLen);
		commitFlag = (buffer.getUint8() != 0); // ENCODED_FLAG_LENGTH

		byte[] sid = buffer.getData(ENCODED_SID_LENGTH);
		long gno = buffer.getLong64();
		source = byteArrayToHex(sid, 0, 4) + "-" + byteArrayToHex(sid, 4, 2) + "-" + byteArrayToHex(sid, 6, 2) + "-"
				+ byteArrayToHex(sid, 8, 2) + "-" + byteArrayToHex(sid, 10, 6);
		gtid = String.format("%s:%d", source, gno);// source + ":" +
													// String.format("%d", gno);

		// ignore gtid info read
		// sid.copy_from((uchar *)ptr_buffer);
		// ptr_buffer+= ENCODED_SID_LENGTH;
		//
		// // SIDNO is only generated if needed, in get_sidno().
		// spec.gtid.sidno= -1;
		//
		// spec.gtid.gno= uint8korr(ptr_buffer);
		// ptr_buffer+= ENCODED_GNO_LENGTH;
	}

	private String byteArrayToHex(byte[] a, int offset, int len) {
		StringBuilder sb = new StringBuilder();
		for (int idx = offset; idx < (offset + len) && idx < a.length; idx++) {
			sb.append(String.format("%02x", a[idx] & 0xff));
		}
		return sb.toString();
	}

	public boolean isCommitFlag() {
		return commitFlag;
	}

	public String getGtid() {
		return gtid;
	}

	public String getSource() {
		return source;
	}
}
